from django.http import HttpResponse
from django.shortcuts import render, redirect

from app01.models import Student


def orm_add(request):
    """功能：增加学生信息"""
    if request.method == "GET":
        return render(request, 'user_add.html')

    # 如果是POST请求，获取前段传递过来的数据
    stu_name = request.POST.get('stu_name')
    age = int(request.POST.get('age'))
    gender = request.POST.get('gender')
    python_score = int(request.POST.get('python_score'))
    address = request.POST.get('address')

    Student.objects.create(stu_name=stu_name, age=age, gender=gender, python_score=python_score, address=address)
    # return HttpResponse('添加成功')
    return redirect('/orm/list/')


def orm_del(request, uid):
    """功能：根据id删除用户信息"""
    Student.objects.get(id=uid).delete()
    # return HttpResponse('删除成功')
    return redirect('/orm/list/')


def orm_list(request):
    """功能：查询所有学生信息"""
    stus = Student.objects.all()
    return render(request, 'index.html', {'stus': stus})


def orm_find_By_id(request, id):
    """根据id查询学生信息"""
    stu = Student.objects.filter(id=id).first()
    print(stu)  # Student object (9)
    print(stu.stu_name)


def orm_update(request, uid):
    """修改用户信息"""
    if request.method == "GET":
        # 查询用户信息，回显到前段页面
        stu = Student.objects.filter(id=uid).first()
        return render(request, 'user_update.html', {'stu': stu})

    # 如果是POST请求，获取前段传递过来的数据
    stu_name = request.POST.get('stu_name')
    age = int(request.POST.get('age'))
    gender = request.POST.get('gender')
    python_score = int(request.POST.get('python_score'))
    address = request.POST.get('address')

    print("111111111111111111111111111111111111111111111")
    Student.objects.filter(id=uid).update(stu_name=stu_name,age=age, gender=gender, python_score=python_score, address=address)
    return redirect('/orm/list/')
